const router = require('koa-router')()
const util = require('../utils/util')
const Dept = require('../models/deptSchema')

// 定义路由前缀
router.prefix('/dept')

// 获取部门列表
router.get('/list', async(ctx) => {

  const { params } =  ctx.request.query
  // console.log('111',deptName)
  // let params = {}
  // if (deptName) params.deptName = deptName
  let rootList = await Dept.find(params)
  // if (deptName) {
    ctx.body = util.success(rootList)
  // } 
  // else {
  //   let tressList = getTreeDept(rootList, null, [])
  //   ctx.body = util.success(tressList)
  // }
})

// 部门 创建/编辑/删除
router.post('/operate', async(ctx) => {
  const { action, _id, ...params } = ctx.request.body
  let res,info;
  try {
    if (action == 'create') {
      await Dept.create(params)
      info = '创建成功'
    } else if (action == 'edit') {
      params.updateTime = new Date()
      await Dept.findByIdAndUpdate(_id, params)
      info = '编辑成功'
    } else if (action == 'delete') {
      await Dept.findByIdAndDelete(_id)
      await Dept.deleteMany({ parentId: {$all: [_id]} })
      info = '删除成功'
    }
    ctx.body = util.success('', info)
  } catch (error) {
    ctx.body = util.error(error.stack)
  }
})

module.exports = router